<?php
$loader->requireOnce('includes/OutPatientFlow/OutPatientFlowProcessor.class.php');
$loader->requireOnce('includes/TreatmentDuration.class.php');

/**
 * Controller HIS Patient actions
 */
class C_MedicalRecord extends Controller {

    function C_MedicalRecord ($template_mod = "general") {
        parent::Controller();
    	if (Celini::getCurrentController() == 'Patient') {
			$menu =& Menu::getInstance();
			$menu->currentSection = 'patient';
		}
        $this->template_mod = $template_mod;
        $this->view->path = 'medical_record';
        $this->logger = LoggerManager::getLogger('controllers.C_MedicalRecord');

    }

	function actionDisplay($patientId = 0, $canEditEncounter = 0) {
		if (isset($_GET['patientId'])) {
			$patientId = $_GET['patientId'];
		}
		if (isset($_GET['canEditEncounter'])) {
			$canEditEncounter = $_GET['canEditEncounter'];
		}
		if (!Celini::newORDO('Patient')->isExist($patientId)) {
			$this->assign('errPatientNotFound', true);
			$this->messages->addMessage(L10nHelper::_("Not found patient id = %s",$patientId));
		} else {
			$user = Celini::newORDO('User');
			$isDoctor = $user->checkRole($this->_me->get_username(), User::ROLE_DOCTOR_ID);
			$this->makeRecordTree($patientId);
			
			$this->patientInfo($patientId);
			$this->assign('isDoctor', $isDoctor);
			$this->assign('canEditEncounter', $canEditEncounter);
			//$this->buildServiceListHTML($patientId);
		}
		return $this->view->render('display.html');
	}
	
	function actionDisplayComponentAjax($patientId = 0) {
		if (isset($_GET['patientId'])) {
			$patientId = $_GET['patientId'];
		}
		if (!Celini::newORDO('Patient')->isExist($patientId)) {
			$this->assign('errPatientNotFound', true);
			$this->messages->addMessage(L10nHelper::_("Not found patient id = %s",$patientId));
		} else {
			$this->makeRecordTree($patientId, true);
			$this->makeRecordTree($patientId, false);
			$this->assign('patientId', $patientId);
		}
		return $this->view->render('display_doctor_view.html');
	}

	function actionAddAjax() {
		$patientId = $_GET['patient_id'];
		$ticket = Celini::newORDO('Ticket');
		$departmentId = $this->_me->get_department_id();
		$ticketId = $ticket->isAnyOpenTicketByDepartment($patientId, $departmentId);
		//$ticketId = $ticket->isAnyOpenTicket($patientId);
		if ($ticketId != false) {
			$record = Celini::newORDO('MedicalRecord');
			$recordId = $record->isAnyOpenRecord($ticketId);
			if ($recordId == false) {
				$record->addNewRecord($patientId, $ticketId);
				$recordId = $record->get_id();
			} else {
				$record->setup($recordId);
			}
			if ($_GET['viewType'] == 'component') {
				return $this->actionDisplayComponentAjax($patientId);
			} else {
				return $this->actionDisplay($patientId, 1);
			}
		}
		return 'NO_TICKET';
	}

	public function actionCloseTreatmentDuration() {
	    $recordId = $_POST['recordId'];
	    $ticketId = Celini::newORDO('MedicalRecord', $recordId)->get('ticket_id');
	    $t = new TreatmentDuration();
	    $result = array('code' => -1, 'link' => '');
	    if ($t->isFullyPaid()) {
            $t->closeTreatmentDuration($ticketId);
            $result['code'] = 1;
            $result['link'] = Celini::link('ViewWorkspace', 'Doctor');
	    }
	    return json_encode($result);
	}
	
	/**
	 * Load demographic info in medical record page
	 * @return html
	 */
    function actionLoadDemographic() {
        $patientId = Celini::newOrdo('MedicalRecord', $_POST['recordId'])->get('patient_id');
        //var_dump($patientId);
        try{            
            $controller = 'C_OdonReception';
            $action = 'LoadReadOnlyPatientAjax';
            if ($patientId > 0) {
                $hisLoader = new HISFileLoader();
                $controllerObj = $hisLoader->getObj($controller);
                $action = 'action' . $action;
                if (method_exists($controllerObj, $action)) {
                    $result['html'] = $controllerObj->$action($patientId);
                } else {
                    throw new Exception("The method $action of class C_".$_POST['controller']." does not exist");
                }                
            } else {                
                throw new Exception("Can not find patient [patient_id=$patientId]");
                
            }
        } catch (Exception $ex) {
            $this->logger->error($ex->getMessage());
            $result['error']['code'] = '1';
        }
        return json_encode($result);   
    }
    
    public function actionLoadCanLamSang() {
        $patientId = Celini::newOrdo('MedicalRecord', $_POST['recordId'])->get('patient_id');
        //var_dump($patientId);
        try{            
            $controller = 'C_CanLamSang';
            $action = 'LoadCanLamSangAjax';
            if ($patientId > 0) {
                $hisLoader = new HISFileLoader();
                $controllerObj = $hisLoader->getObj($controller);
                $action = 'action' . $action;
                if (method_exists($controllerObj, $action)) {
                    $result['html'] = $controllerObj->$action($patientId);
                } else {
                    throw new Exception("The method $action of class C_".$_POST['controller']." does not exist");
                }                
            } else {                
                throw new Exception("Can not find patient [patient_id=$patientId]");
                
            }
        } catch (Exception $ex) {
            $this->logger->error($ex->getMessage());
            $result['error']['code'] = '1';
        }
        return json_encode($result);   
    }
	
	private function makeRecordTree($patientId) {
		$record = Celini::newORDO('MedicalRecord');
		$departmentId = $this->_me->get_department_id();
		$res = $record->getAllRecordOfPatient($patientId, $departmentId, $status);

		$recordTree = array();
		$newRecordData = array();
		$today = date('Y-m-d');
		$newRecord = false;
		foreach ($res as $record) {
		    $name = 'PK ' . $record['date'];
            $id = $record['medical_record_id'];
		    if ($record['date'] == $today) {
		        $newRecord = true;
		        $newRecordData = array('record_id' => $id, 'name' => $name);
		    } else {
		         $recordTree[] = array('record_id' => $id, 'name' => $name);    
		    }						
		}
		
		if ($newRecord == true) {
		    $this->assign('newRecord', $newRecordData);
		}
		
		if (sizeof($recordTree) > 0) {
		    $this->assign('recordTree', $recordTree);
			
		}
	}

	private function patientInfo($patientId) {
		$person = Celini::newORDO('Person', $patientId);
		$this->assign('patientId', $patientId);
	}

	/**
	 * Build service list HTML of current open ticket of a patient
	 *
	 * @param int $patientId Patient Id
	 */
	private function buildServiceListHTML($patientId) {
        $ticket = Celini::newORDO('Ticket');
        $departmentId = $this->_me->get_department_id();
        $res = $ticket->getAllTicketOfPatientByDepartment($patientId, $departmentId, true);
        if (count($res) > 0) {
            $this->assign('ticketId', $res[0]['ticket_id']);
        	$this->assign('currentTicket', $res[0]['name']);
            $serviceList  =   OutPatientFlowProcessor::renderTicketItemListHMLT($res[0]['ticket_id']);
            $this->assign('serviceListHTML', $serviceList);
        }
	}
}
?>